package org.jeecg.modules.systemextend.systemextend.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SysTenantVo;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.common.utils.MapBeanUtils;
import org.jeecg.modules.cougradesessionyear.entity.CouGradesessionYear;
import org.jeecg.modules.cougradesessionyear.service.ICouGradesessionYearService;
import org.jeecg.modules.grade.entity.CouGrade;
import org.jeecg.modules.grade.service.ICouGradeService;
import org.jeecg.modules.schoolyear.entity.CouSchoolYear;
import org.jeecg.modules.schoolyear.service.ICouSchoolYearService;
import org.jeecg.modules.semester.entity.CouSemester;
import org.jeecg.modules.semester.service.ICouSemesterService;
import org.jeecg.modules.systemextend.systemextend.po.CopyCloneTenant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: sys_third_account
 * @author: baochangrong
 * @Date:   2022-08-03
 * @Version: V1.0
 */
@Api(tags="sys_tenant_extend")
@RestController
@RequestMapping("/systemextend/systemextend/sysTenantExtendExtend")
@Slf4j
public class SysTenantExtendController {
    @Autowired
    ISysBaseAPI sysBaseAPI;
    @Autowired
    ICouSemesterService couSemesterService;
    @Autowired
    ICouSchoolYearService couSchoolYearService;
    @Autowired
    ICouGradesessionYearService couGradesessionYearService;
    @Autowired
    ICouGradeService couGradeService;
    /**
     * 批量创建租户基础信息：管理员用户、角色等
     *
     * @param requestParm
     * @param req
     * @return
     */
    @AutoLog(value = "批量创建租户基础信息：管理员用户、角色等")
    @ApiOperation(value = "批量创建租户基础信息：管理员用户、角色等", notes = "批量创建租户基础信息：管理员用户、角色等")
    @PostMapping(value = "/createTenantRoleUser")
    public Result<?> createTenantAdminRoleUser(@RequestBody Object requestParm, HttpServletRequest req) {
        //创建角色：为指定租户创建管理员角色
        //创建用户：为指定租户创建管理员用户
        //创建角色用户关系（授权）
        Map requestParmMap = JSONObject.parseObject(JSONObject.toJSONString(requestParm), Map.class);
        //此map给vo赋值的函数：可以考虑map转vo，或json转vo
        CopyCloneTenant copyCloneTenant = MapBeanUtils.map2Bean(CopyCloneTenant.class,requestParmMap);

        //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值克隆给vo
//            BaseApiEntity baseApiEntity = sysInfo.querySysInfoCloneObj(req,sysTenantVo); //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值给vo


        String ids = requestParmMap.get("ids").toString();
        if(oConvertUtils.isEmpty(copyCloneTenant) || oConvertUtils.isEmpty(copyCloneTenant.getSourceSysTenantId()) ){
            copyCloneTenant.setSourceSysTenantId(ids);
        }
        int id =0;
        if(oConvertUtils.isNotEmpty(ids) && ids.indexOf(",")==-1 ){
            id = Integer.valueOf(ids);
        }
        String newUserId = sysBaseAPI.createTenantAdminRoleUser(id);
        LoginUser newUser = sysBaseAPI.getUserById(newUserId);
        return Result.OK("创建管理员成功!管理员账号："+newUser.getUsername());
    }
    /**
     * 批量复制克隆租户基础信息：菜单、部门、学期、学年、届级、年级等
     *
     * @param requestParm
     * @param req
     * @return
     */
    @AutoLog(value = "批量复制克隆租户基础信息：菜单、部门、学期、学年、届级、年级等")
    @ApiOperation(value = "批量复制克隆租户基础信息：菜单、部门、学期、学年、届级、年级等", notes = "批量复制克隆租户基础信息：菜单、部门、学期、学年、届级、年级等")
    @PostMapping(value = "/copyCloneTenantBaseInfo")
    public Result<?> copyCloneTenantBaseInfo(@RequestBody Object requestParm, HttpServletRequest req) {
        Map requestParmMap = JSONObject.parseObject(JSONObject.toJSONString(requestParm), Map.class);
        //此map给vo赋值的函数：可以考虑map转vo，或json转vo
        CopyCloneTenant copyCloneTenant = MapBeanUtils.map2Bean(CopyCloneTenant.class,requestParmMap);

        //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值克隆给vo
//            BaseApiEntity baseApiEntity = sysInfo.querySysInfoCloneObj(req,sysTenantVo,false); //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值给vo


        //复制菜单
        //复制角色
        //复制权限
        //复制部门
        //创建管理员用户
        sysBaseAPI.copyCloneTenantMenuRoleDepart(copyCloneTenant.getSourceSysTenantId(),copyCloneTenant.getTargetSysTenantId(),copyCloneTenant.getCopyCloneObjTypes());


        Map<String, Object> queryMap = new HashMap<String, Object>();
        String copyCloneObjTypes = copyCloneTenant.getCopyCloneObjTypes();
        //复制学期:目标不存在则复制，存在则忽略
        if(copyCloneObjTypes.indexOf("CouSemester") != -1) {
            queryMap.put("tenant_id", copyCloneTenant.getSourceSysTenantId());
            List<CouSemester> sourceCouSemesterList = couSemesterService.listByMap(queryMap);
            queryMap.put("tenant_id", copyCloneTenant.getTargetSysTenantId());
            List<CouSemester> targetCouSemesterList = couSemesterService.listByMap(queryMap);
            if (oConvertUtils.listIsNotEmpty(sourceCouSemesterList) && oConvertUtils.listIsEmpty(targetCouSemesterList)) {
                for (CouSemester p : sourceCouSemesterList) {
                    p.setId(null);
                    p.setTenantId(copyCloneTenant.getTargetSysTenantId());
                }
                couSemesterService.saveBatch(sourceCouSemesterList);
            }
        }
        //复制学年:目标不存在则复制，存在则忽略
        if(copyCloneObjTypes.indexOf("CouSchoolYear") != -1) {
            queryMap.put("tenant_id", copyCloneTenant.getSourceSysTenantId());
            List<CouSchoolYear> sourceCouSchoolYearList = couSchoolYearService.listByMap(queryMap);
            queryMap.put("tenant_id", copyCloneTenant.getTargetSysTenantId());
            List<CouSchoolYear> targetCouSchoolYearList = couSchoolYearService.listByMap(queryMap);
            if (oConvertUtils.listIsNotEmpty(sourceCouSchoolYearList) && oConvertUtils.listIsEmpty(targetCouSchoolYearList)) {
                for (CouSchoolYear p : sourceCouSchoolYearList) {
                    p.setId(null);
                    p.setTenantId(copyCloneTenant.getTargetSysTenantId());
                }
                couSchoolYearService.saveBatch(sourceCouSchoolYearList);
            }
        }
        //复制届级:目标不存在则复制，存在则忽略
        if(copyCloneObjTypes.indexOf("CouGradesessionYear") != -1) {
            queryMap.put("tenant_id", copyCloneTenant.getSourceSysTenantId());
            List<CouGradesessionYear> sourceCouGradesessionYearList = couGradesessionYearService.listByMap(queryMap);
            queryMap.put("tenant_id", copyCloneTenant.getTargetSysTenantId());
            List<CouGradesessionYear> targetCouGradesessionYearList = couGradesessionYearService.listByMap(queryMap);
            if (oConvertUtils.listIsNotEmpty(sourceCouGradesessionYearList) && oConvertUtils.listIsEmpty(targetCouGradesessionYearList)) {
                for (CouGradesessionYear p : sourceCouGradesessionYearList) {
                    p.setId(null);
                    p.setTenantId(copyCloneTenant.getTargetSysTenantId());
                }
                couGradesessionYearService.saveBatch(sourceCouGradesessionYearList);
            }
        }
        //复制年级
        if(copyCloneObjTypes.indexOf("CouGrade") != -1) {
            queryMap.put("tenant_id", copyCloneTenant.getSourceSysTenantId());
            List<CouGrade> sourceCouGradeList = couGradeService.listByMap(queryMap);
            queryMap.put("tenant_id", copyCloneTenant.getTargetSysTenantId());
            List<CouGrade> targetCouGradeList = couGradeService.listByMap(queryMap);
            if (oConvertUtils.listIsNotEmpty(sourceCouGradeList) && oConvertUtils.listIsEmpty(targetCouGradeList)) {
                for (CouGrade p : sourceCouGradeList) {
                    p.setId(null);
                    p.setTenantId(copyCloneTenant.getTargetSysTenantId());
                }
                couGradeService.saveBatch(sourceCouGradeList);
            }
        }
        //复制科目
        //复制班级（注意班级所属年级，注意学期学年）
        //复制学生
        //复制班级学生关系
        //复制老师
        //复制老师科目关系
        //复制班级科目老师教室任教关系（，注意学期学年）
        //复制教学计划（，注意学期学年，教学计划分配关系可以不复制手动分配即可）
        //复制课表模板
        //复制课表模板应用分配关系（可考虑手动分配）
        //复制课表（注意对象id的替换）
        //复制考试（含计分规则、评分标准等）
        //复制试卷（含评分标准、题型标准等、标准应用关系等）

        return Result.OK("复制克隆成功!");
    }
}
